<?php
/* Copyright (C) 2007-2008 Laurent Destailleur  <eldy@users.sourceforge.net>
 * Copyright (C) 2010 Jean-François FERRY <jfefe@aternatik.fr>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 */

/**
 *      \file       ovhsms/ovhsms.class.php
 *      \ingroup    ovhsms
 *      \brief      This file allow to send sms with an OVH account
 *		\author		Jean-François FERRY
 */

// Put here all includes required by your class file
//require_once(DOL_DOCUMENT_ROOT."/commonobject.class.php");
//require_once(DOL_DOCUMENT_ROOT."/societe.class.php");
//require_once(DOL_DOCUMENT_ROOT."/product.class.php");
//require_once(NUSOAP_PATH.'/nusoap.php');

/**
 *      \class      OvhSms
 *      \brief      Put here description of your class
 *		\remarks	Put here some comments
 */
class OvhSms  extends CommonObject
{
	var $db;							//!< To store db handler
	var $error;							//!< To return error code (or message)
	var $errors=array();				//!< To return several error codes (or messages)
	var $element='ovhsms';			//!< Id that identify managed object
	var $session;
    var $id;
    var $account;
    var $fk_soc;
    var $expe;
    var $dest;
    var $message;
    var $validity;
    var $class;
    var $deferred;
    var $priority;


    /**
     *      \brief      Constructor
     *      \param      DB      Database handler
     */
    function OvhSms($DB)
    {
       global $conf, $langs;
        $this->db = $DB;

        // Réglages par défaut
        $this->validity = '10';
        $this->class = '2';
        $this->priority = '3';

        
		
       $this->login = $conf->global->OVHSMS_NICK;
       $this->password = $conf->global->OVHSMS_PASS;
       $this->account = $conf->global->OVHSMS_ACCOUNT;
   
	   
	   // NuSoap not working :(
	   //$client = new nusoap_client($conf->global->OVHSMS_SOAPURL,true);
	   //$this->soap= $client->getProxy();
		
		// Set the WebService URL
        dol_syslog("Create nusoap_client for URL=".$conf->global->OVHSMS_SOAPURL);
		$this->soap = new SoapClient($conf->global->OVHSMS_SOAPURL);
		
		
		$language = "fr";
		$multisession = false;
		try {
			$this->session = $this->soap->login($this->login,$this->password,$language,$multisession);	   	
		}
		catch(SoapFault $fault) {

           dol_syslog("Error nusoap_client for URL=".$conf->global->OVHSMS_SOAPURL. ' : '.$fault);
           return 0;

       }
		
			   
    

       
    }

	function logout() {
      $this->soap->logout($this->session);
      return 1;
   }


   /**
   *      \brief      Create an account
   *      \param      user           User that create
   *      \param      notrigger       0=launch triggers after, 1=disable triggers
   *      \return     account		String with the OVH SMS Account
   */
   function create($user, $notrigger=0)
   {
      global $conf, $langs;
      $error=0;

      // Clean parameters
      if (isset($this->account)) $this->account=trim($this->account);
      if (isset($this->fk_soc)) $this->fk_soc=trim($this->fk_soc);
      //...

      // Check parameters
      // Put here code to add control on parameters values

      // Insert request
      $sql = "INSERT INTO ".MAIN_DB_PREFIX."ovhsms_account(";
      $sql.= " ovh_account,";
      $sql.= " fk_soc";
      //...
      $sql.= ") VALUES (";
      $sql.= " '".$this->account."',";
      $sql.= " '".$this->fk_soc."'";
      //...
      $sql.= ")";

      $this->db->begin();

      dol_syslog(get_class($this)."::create sql=".$sql, LOG_DEBUG);
      $resql=$this->db->query($sql);
      if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }

      if (! $error)
      {
         $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."mytable");

         if (! $notrigger)
         {
            // Uncomment this and change MYOBJECT to your own tag if you
            // want this action call a trigger.

            //// Call triggers
            //include_once(DOL_DOCUMENT_ROOT . "/interfaces.class.php");
            //$interface=new Interfaces($this->db);
            //$result=$interface->run_triggers('MYOBJECT_CREATE',$this,$user,$langs,$conf);
            //if ($result < 0) { $error++; $this->errors=$interface->errors; }
            //// End call triggers
         }
      }

      // Commit or rollback
      if ($error)
      {
         foreach($this->errors as $errmsg)
         {
            dol_syslog(get_class($this)."::create ".$errmsg, LOG_ERR);
            $this->error.=($this->error?', '.$errmsg:$errmsg);
         }
         $this->db->rollback();
         return -1*$error;
      }
      else
      {
         $this->db->commit();
         return $this->id;
      }
   }



    /**
     *    \brief      Retourne le compte OVH associé s'il existe
     *    \param      id          id societe client
     *    \return     int         <0 if KO, >0 if OK
     */
    function fetch_account($id)
    {
    	global $langs;
      $sql = "SELECT";
		$sql.= " t.rowid,";
		$sql.= " t.ovh_account";
      //$sql.= " t.numberFrom";
      //$sql.= " t.smsquota, t.date_crea";
      $sql.= " FROM ".MAIN_DB_PREFIX."ovhsms_account as t";
      $sql.= " WHERE t.fk_soc = ".$id;

    	dol_syslog(get_class($this)."::fetch sql=".$sql, LOG_DEBUG);
        $resql=$this->db->query($sql);
        if ($resql)
        {
            if ($this->db->num_rows($resql))
            {
                $obj = $this->db->fetch_object($resql);

                $this->id    = $obj->rowid;
                $this->account = $obj->ovh_account;
                $this->fk_soc = $obj->fk_soc;
                $this->numberFrom = $obj->numberFrom;
                $this->smsquota = $obj->smsquota;
                $this->date_crea = $obj->date_crea;

            }
            $this->db->free($resql);

            return $this->account;
        }
        else
        {
      	    $this->error="Error ".$this->db->lasterror();
            dol_syslog(get_class($this)."::fetch ".$this->error, LOG_ERR);
            return -1;
        }
    }


    /**
     *      \brief      Update database
     *      \param      user        	User that modify
     *      \param      notrigger	    0=launch triggers after, 1=disable triggers
     *      \return     int         	<0 if KO, >0 if OK

    function update($user=0, $notrigger=0)
    {
    	global $conf, $langs;
		$error=0;

		// Clean parameters
        if (isset($this->prop1)) $this->prop1=trim($this->prop1);
        if (isset($this->prop2)) $this->prop2=trim($this->prop2);
		//...

		// Check parameters
		// Put here code to add control on parameters values

        // Update request
        $sql = "UPDATE ".MAIN_DB_PREFIX."mytable SET";
        $sql.= " field1=".(isset($this->field1)?"'".addslashes($this->field1)."'":"null").",";
        $sql.= " field2=".(isset($this->field2)?"'".addslashes($this->field2)."'":"null")."";
		//...
        $sql.= " WHERE rowid=".$this->id;

		$this->db->begin();

		dol_syslog(get_class($this)."::update sql=".$sql, LOG_DEBUG);
        $resql = $this->db->query($sql);
    	if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }

		if (! $error)
		{
			if (! $notrigger)
			{
	            // Uncomment this and change MYOBJECT to your own tag if you
	            // want this action call a trigger.

	            //// Call triggers
	            //include_once(DOL_DOCUMENT_ROOT . "/interfaces.class.php");
	            //$interface=new Interfaces($this->db);
	            //$result=$interface->run_triggers('MYOBJECT_MODIFY',$this,$user,$langs,$conf);
	            //if ($result < 0) { $error++; $this->errors=$interface->errors; }
	            //// End call triggers
	    	}
		}

        // Commit or rollback
		if ($error)
		{
			foreach($this->errors as $errmsg)
			{
	            dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
	            $this->error.=($this->error?', '.$errmsg:$errmsg);
			}
			$this->db->rollback();
			return -1*$error;
		}
		else
		{
			$this->db->commit();
			return 1;
		}
    }
*/

 	/**
	 *   \brief      Delete object in database
     *	\param      user        	User that delete
     *   \param      notrigger	    0=launch triggers after, 1=disable triggers
	 *	\return		int				<0 if KO, >0 if OK
	 */
	function delete($user, $notrigger=0)
	{
		global $conf, $langs;
		$error=0;

      $sql = "DELETE FROM ".MAIN_DB_PREFIX."llx_ovhsms_account";
		$sql.= " WHERE rowid=".$this->id;

		$this->db->begin();

		dol_syslog(get_class($this)."::delete sql=".$sql);
		$resql = $this->db->query($sql);
    	if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }

		if (! $error)
		{
			if (! $notrigger)
			{
				// Uncomment this and change MYOBJECT to your own tag if you
		        // want this action call a trigger.

		        //// Call triggers
		        //include_once(DOL_DOCUMENT_ROOT . "/interfaces.class.php");
		        //$interface=new Interfaces($this->db);
		        //$result=$interface->run_triggers('MYOBJECT_DELETE',$this,$user,$langs,$conf);
		        //if ($result < 0) { $error++; $this->errors=$interface->errors; }
		        //// End call triggers
			}
		}

        // Commit or rollback
		if ($error)
		{
			foreach($this->errors as $errmsg)
			{
	            dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR);
	            $this->error.=($this->error?', '.$errmsg:$errmsg);
			}
			$this->db->rollback();
			return -1*$error;
		}
		else
		{
			$this->db->commit();
			return 1;
		}
	}

   /*
   * Envoi d'un sms
   */
   function SmsSend() {
      //telephonySmsSend
      try
      {
         $resultsend = $this->soap->telephonySmsSend($this->session, $this->account, $this->expe, $this->dest, $this->message, $this->validity, $this->class, $this->deferred, $this->priority);
         return $resultsend;
      }
      catch(SoapFault $fault)
      {
         $errmsg="Error ".$fault->faultstring;
         dol_syslog(get_class($this)."::SmsSend ".$errmsg, LOG_ERR);

         $this->error.=($this->error?', '.$errmsg:$errmsg);
         return -1;
      }
      return -1;
   }


  function printListAccount() {
   $resultaccount = $this->getSmsListAccount();
   print '<select name="ovh_account" id="ovh_account">';
   foreach ($resultaccount as $accountlisted) {
      print '<option value="'.$accountlisted.'">'.$accountlisted.'</option>';
   }
   print '</select>';
  }

  /* Get a list of customer using $account
  function getcustomerbyaccount() {
     global $conf, $langs;

     $sql = "SELECT";
     $sql.= " fk_soc, ,";
     $sql.= " t.ovh_account";
     $sql.= " t.numberFrom";
     $sql.= " t.smsquota, t.date_crea";
     $sql.= " FROM ".MAIN_DB_PREFIX."ovhsms_account as t";
     $sql.= " WHERE t.fk_soc = ".$id;

     dol_syslog(get_class($this)."::fetch sql=".$sql, LOG_DEBUG);
     $resql=$this->db->query($sql);
     if ($resql)
     {
        if ($this->db->num_rows($resql))
        {
           $obj = $this->db->fetch_object($resql);
        }
     }
  }
*/

  function getSmsListAccount()
  {
   //telephonySmsAccountList
   return $this->soap->telephonySmsAccountList($this->session);
  }

  function CreditLeft()
  {
   return $this->soap->telephonySmsCreditLeft($this->session, $this->account);
  }

	// http://www.ovh.com/soapi/fr/index.xml?method=telephonySmsHistory
  function SmsHistory($account,$start=0,$limit=50,$sortfield="date",$sortorder="asc")
  {
   return $this->soap->telephonySmsHistory($this->session, $this->account, "");
   return $this->soap->telephonySmsHistory($this->session, $this->account, "", "", $start, $limit, $sortfield,$sortorder, "");
  }

  function SmsSenderList($account)
  {
     try {
        $telephonySmsSenderList = $this->soap->telephonySmsSenderList($this->session, $this->account);
        return $telephonySmsSenderList;
     }
     catch(SoapFault $fault) {
         $errmsg="Error ".$fault->faultstring;
         dol_syslog(get_class($this)."::SmsSenderList ".$errmsg, LOG_ERR);
         $this->error.=($this->error?', '.$errmsg:$errmsg);
         return -1;
      }
     return -1;
  }



/**
 * 		\brief		Show html area for list of contacts
 *		\param		conf		Object conf
 * 		\param		lang		Object lang
 * 		\param		db			Database handler
 * 		\param		objsoc		Third party object
 */
function show_sms_contacts($conf,$langs,$db,$objsoc)
{
	global $user;
	global $bc;

	$contactstatic = new Contact($db);

	print_titre($langs->trans("ContactsForCompany"));
	print '<table class="noborder" width="100%">';

	print '<tr class="liste_titre"><td>'.$langs->trans("Name").'</td>';
	print '<td>'.$langs->trans("Tel").'</td>';
	print '<td>'.$langs->trans("Portable").'</td>';
	print "<td>&nbsp;</td>";

	print "</tr>";

	$sql = "SELECT p.rowid, p.name, p.firstname, p.poste, p.phone, p.phone_mobile, p.fax, p.email, p.note ";
	$sql .= " FROM ".MAIN_DB_PREFIX."socpeople as p";
	$sql .= " WHERE p.fk_soc = ".$objsoc->id;
	$sql .= " ORDER by p.datec";

	$result = $db->query($sql);
	$i = 0;
	$num = $db->num_rows($result);
	$var=true;

	if ($num)
	{
		while ($i < $num)
		{
			$obj = $db->fetch_object($result);
			$var = !$var;

			print "<tr ".$bc[$var].">";

			print '<td>';
            $contactstatic->id = $obj->rowid;
            $contactstatic->name = $obj->name;
            $contactstatic->firstname = $obj->firstname;
            print $contactstatic->getNomUrl(1);
			print '</td>';

			// Lien click to dial
			print '<td id="contact_tel" >';
         print '<strong class="choose_tel">'.$obj->phone.'</strong>';
			print '</td>';
         print '<td id="contact_mobile" class="choose_tel">';
         print '<strong class="choose_tel">'.$obj->phone_mobile.'</strong>';

			print '</td>';


			print '<td align="center">';
			print '<a href="'.DOL_URL_ROOT.'/contact/fiche.php?action=edit&amp;id='.$obj->rowid.'">';
			print img_edit();
			print '</a></td>';



			print "</tr>\n";
			$i++;
		}
	}
	else
	{
		print "<tr ".$bc[$var].">";
		print '<td>'.$langs->trans("NoContactsYetDefined").'</td>';
		print "</tr>\n";
	}
	print "</table>\n";

	print "<br>\n";
}


	/**
	 *		\brief      Load an object from its id and create a new one in database
	 *		\param      fromid     		Id of object to clone
	 * 	 	\return		int				New id of clone
	 */
	function createFromClone($fromid)
	{
		global $user,$langs;

		$error=0;

		$object=new Skeleton_class($this->db);

		$this->db->begin();

		// Load source object
		$object->fetch($fromid);
		$object->id=0;
		$object->statut=0;

		// Clear fields
		// ...

		// Create clone
		$result=$object->create($user);

		// Other options
		if ($result < 0)
		{
			$this->error=$object->error;
			$error++;
		}

		if (! $error)
		{



		}

		// End
		if (! $error)
		{
			$this->db->commit();
			return $object->id;
		}
		else
		{
			$this->db->rollback();
			return -1;
		}
	}


	/**
	 *		\brief		Initialise object with example values
	 *		\remarks	id must be 0 if object instance is a specimen.
	 */
	function initAsSpecimen()
	{
		$this->id=0;
		$this->prop1='prop1';
		$this->prop2='prop2';
	}

}
?>